package com.projectzqjz.parttimework.ui.fragment;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.projectzqjz.parttimework.R;
import com.projectzqjz.parttimework.adapter.Part3HomeAdapter;
import com.projectzqjz.parttimework.adapter.PartBannerEntity;
import com.projectzqjz.parttimework.base.BaseFragment;
import com.projectzqjz.parttimework.entity.BeanXBanner;
import com.projectzqjz.parttimework.entity.DailyEntity;
import com.projectzqjz.parttimework.entity.PartBaseEntity;
import com.projectzqjz.parttimework.myinterface.Part3HomeRefresh;
import com.projectzqjz.parttimework.net.MyCallback;
import com.projectzqjz.parttimework.net.NoValidationTask;
import com.projectzqjz.parttimework.ui.activity.PartBannerDetailActivity;
import com.projectzqjz.parttimework.ui.activity.PartDetailActivity;
import com.projectzqjz.parttimework.ui.activity.PartHomeCenterActivity;
import com.projectzqjz.parttimework.ui.activity.PartSearchActivity;
import com.projectzqjz.parttimework.utils.ScreenUtil;
import com.stx.xhb.xbanner.XBanner;


import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Response;

public class PopularPartTimeFragment extends BaseFragment {
    @BindView(R.id.view_status_bar_place)
    View statusBarPlace;
    @BindView(R.id.xBanner)
    XBanner mXBanner;
    @BindView(R.id.ll_pot)
    LinearLayout llPot;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.recyclerView1)
    RecyclerView recyclerView1;
    private boolean isFirst = true;
    private List<View> views;
    private Part3HomeAdapter part3HomeAdapter = null;
    private List<DailyEntity> list = new ArrayList<>();

    private Part3HomeAdapter part3HomeAdapter1 = null;
    private List<DailyEntity> list1 = new ArrayList<>();


    private List<PartBannerEntity> bannerEntities = new ArrayList<>();


    @Override
    public View setContentView(LayoutInflater inflater) {
        return inflater.inflate(R.layout.fragment_part_home, null);
    }

    @OnClick({R.id.ll_search,R.id.rel_bm_more,R.id.rel_daily_more})
    public void onViewClicked(View view) {
        if (ScreenUtil.isFastClick()) {
            return;
        }
        switch (view.getId()){
            case R.id.ll_search://搜索
                startActivity(new Intent(getActivity(), PartSearchActivity.class));
                break;
            case R.id.rel_daily_more://高新推荐
                startActivity(new Intent(getActivity(), PartHomeCenterActivity.class).putExtra("type", "0"));
                break;
            case R.id.rel_bm_more://宝妈专场
                startActivity(new Intent(getActivity(), PartHomeCenterActivity.class).putExtra("type", "1"));
                break;
        }
    }


    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        ViewGroup.LayoutParams params = statusBarPlace.getLayoutParams();
        params.height = ScreenUtil.getStatusBarHeight(getContext());
        statusBarPlace.setLayoutParams(params);
        initView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (isFirst) {
                isFirst = false;
                //初始化banner和recycleView组件
                getBanner();
                getJobList("4");//获取高新推荐
                //宝马专场
                String type2 = "5";
                getJobList(type2);//获取宝妈专场
            }
        }
    }

    private void initView() {

        LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        if (part3HomeAdapter == null) {
            part3HomeAdapter = new Part3HomeAdapter(list, new Part3HomeRefresh() {
                @Override
                public void refresh() {
                    //刷新高薪兼职
                    getJobList("4");//获取高新推荐
                }
            });
        }
        recyclerView.setHasFixedSize(true);
        recyclerView.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        recyclerView.setLayoutManager(manager);
        recyclerView.setAdapter(part3HomeAdapter);
        part3HomeAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转兼职详情
                startActivity(new Intent(getActivity(), PartDetailActivity.class).putExtra("jobId", list.get(position).getJobId()));
            }
        });


        LinearLayoutManager manager1 = new LinearLayoutManager(getActivity());
        if (part3HomeAdapter1 == null) {
            part3HomeAdapter1 = new Part3HomeAdapter(list1, new Part3HomeRefresh() {
                @Override
                public void refresh() {
                    //刷新宝妈兼职
                    getJobList("5");//获取宝妈专场
                }
            });
        }
        recyclerView1.setHasFixedSize(true);
        recyclerView1.setNestedScrollingEnabled(false);
        // 第一种，直接取消动画
        RecyclerView.ItemAnimator animator1 = recyclerView1.getItemAnimator();
        if (animator1 instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator1).setSupportsChangeAnimations(false);
        }
        recyclerView1.setLayoutManager(manager1);
        recyclerView1.setAdapter(part3HomeAdapter1);
        part3HomeAdapter1.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                //跳转兼职详情
                startActivity(new Intent(getActivity(), PartDetailActivity.class).putExtra("jobId", list1.get(position).getJobId()));
            }
        });

        //设置广告图片点击事件
        mXBanner.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, Object model, View view, int position) {
                //点击banner事件 跳转落地页
                String action = bannerEntities.get(position).getAction();
                switch (action) {
                    case "0":
                        break;
                    case "1":
                        break;
                    case "2":
                        break;
                    case "3":
                        String url = bannerEntities.get(position).getToUrl();
                        startActivity(new Intent(getActivity(), PartBannerDetailActivity.class).putExtra("url", url));
                        break;
                }
            }
        });
        //加载广告图片
        mXBanner.loadImage(new XBanner.XBannerAdapter() {
            @Override
            public void loadBanner(XBanner banner, Object model, View view, int position) {
                //此处适用Fresco加载图片，可自行替换自己的图片加载框架
                SimpleDraweeView dView = (SimpleDraweeView) view;
                BeanXBanner listBean = ((BeanXBanner) model);
                String url = listBean.getImgUrl();
                dView.setImageURI(Uri.parse(url));
            }
        });
        mXBanner.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int i, float v, int i1) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < views.size(); i++) {
                    if (i == position) {
                        views.get(i).setBackgroundResource(R.drawable.xbanner_pot_select);
                    } else {
                        views.get(i).setBackgroundResource(R.drawable.xbanner_pot_normal);
                    }
                }

            }

            @Override
            public void onPageScrollStateChanged(int i) {

            }
        });
    }


    /**
     * 初始化点
     */
    private void initPot(List<BeanXBanner> list) {
        views = new ArrayList<>();
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        for (int i = 0; i < list.size(); i++) {
            TextView v = new TextView(getActivity());
            layoutParams.setMargins(0, 0, ScreenUtil.dip2px(Objects.requireNonNull(getActivity()), 8), 0);
            if (i == 0) {
                v.setBackgroundResource(R.drawable.xbanner_pot_select);
            } else {
                v.setBackgroundResource(R.drawable.xbanner_pot_normal);
            }

            v.setLayoutParams(layoutParams);
            views.add(v);
            llPot.addView(v);
        }
    }


    //获取banner
    private void getBanner() {
        NoValidationTask.getApiService().getBanner().enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (jsonArray.size() > 0) {
                    for (int i = 0; i < jsonArray.size(); i++) {
                        PartBannerEntity partBannerEntity = new PartBannerEntity();
                        partBannerEntity.setAction(jsonArray.getJSONObject(i).getInteger("action") + "");
                        partBannerEntity.setBannerUrl(jsonArray.getJSONObject(i).getString("url"));
                        partBannerEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                        partBannerEntity.setToUrl(jsonArray.getJSONObject(i).getString("fileUrl"));
                        bannerEntities.add(partBannerEntity);
                    }
                    List<BeanXBanner> list = new ArrayList<>();
                    for (int i = 0; i < bannerEntities.size(); i++) {
                        BeanXBanner beanXBanner = new BeanXBanner();
                        beanXBanner.setImgUrl(bannerEntities.get(i).getBannerUrl());
                        list.add(beanXBanner);
                    }
                    initPot(list);
                    //刷新数据之后，需要重新设置是否支持自动轮播
                    mXBanner.setAutoPlayAble(list.size() > 1);
                    mXBanner.setBannerData(R.layout.layout_fresco_imageview, list);
                }
            }

            @Override
            protected void onFailure(Throwable t) {

            }
        });
    }

    //获取职位列表
    private void getJobList(String type) {
        NoValidationTask.getApiService().getPart3HomeJob(type).enqueue(new MyCallback<PartBaseEntity>(getActivity()) {
            @Override
            protected void onSuccess(Response<PartBaseEntity> response) {
                assert response.body() != null;
                String jsonStr = JSONObject.toJSONString(response.body().getData());
                JSONArray jsonArray = JSONArray.parseArray(jsonStr);
                if (jsonArray.size() > 0) {
                    if (type.equals("4")) {//高新推荐
                        list.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            dailyEntity.setTime(jsonArray.getJSONObject(i).getString("time"));
                            list.add(dailyEntity);
                        }
                    } else {//宝妈专场
                        list1.clear();
                        for (int i = 0; i < jsonArray.size(); i++) {
                            DailyEntity dailyEntity = new DailyEntity();
                            dailyEntity.setTitle(jsonArray.getJSONObject(i).getString("title"));
                            dailyEntity.setJobId(jsonArray.getJSONObject(i).getInteger("id") + "");
                            dailyEntity.setLabel(jsonArray.getJSONObject(i).getString("jobPayType"));
                            dailyEntity.setMoney(jsonArray.getJSONObject(i).getInteger("jobPay") + "");
                            dailyEntity.setUnit(jsonArray.getJSONObject(i).getString("jobPayUnit"));
                            dailyEntity.setGsName(jsonArray.getJSONObject(i).getString("jobCompany"));
                            dailyEntity.setLocation(jsonArray.getJSONObject(i).getString("jobAddress"));
                            dailyEntity.setTime(jsonArray.getJSONObject(i).getString("time"));
                            list1.add(dailyEntity);
                        }
                    }

                }
                if (type.equals("4")) {
                    part3HomeAdapter.notifyDataSetChanged();
                } else {
                    part3HomeAdapter1.notifyDataSetChanged();
                }

            }

            @Override
            protected void onFailure(Throwable t) {
            }
        });
    }
}
